<?
/**
*  号码管理
*  2014/5/11
*/
include("database.php");

include("session.php");
require("functions.php");
require("ajax_base.php");
require("xml_excel.php");

$action = $_GET['action'];

$table_name = "qc_call";

if($action == "del") {
	$db->doDelete($table_name, 'id='.$_GET['id']); 
	echo "ok";

} else if($action == "list") {
	$condition = "1=1";
	if(isset($_GET['task_id'])) {
		$condition .= " and a.task_id=".$_GET['task_id'];
	}
	if(isset($_GET['task_name'])) {
		$condition .= " and b.task_name='".$_GET['task_name']."'";
	}
	if(isset($_GET['call_result'])) {
		$condition .= " and a.call_result=".$_GET['call_result'];
	}
	if(isset($_GET['user_select_key'])) {
			$condition .= " and a.user_select_key='".$_GET['user_select_key']."'";
	}
	if(isset($_GET['call_status'])) {
		$condition .= " and a.call_status=".$_GET['call_status'];
	}
	if(isset($_GET['date_range'])) {
		$arr = explode("_", $_GET['date_range']);
		$condition .= " and a.call_time between '".$arr[0]."' and '".$arr[1]."'";
	}
	if(isset($_GET['telephone'])) {
		$condition .= " and a.telephone='". trim($_GET['telephone'])."'";
	}
	if($_SESSION['user_flag'] == "user") {
		$condition .= " and b.user_id = ".$_SESSION['user_id'];
	}
	$sql = "select a.id,b.task_name, b.callout_number, a.telephone,call_result,call_time,fail_desc, listen_time_long, user_select_key,  call_status, post_time, '' as op_link, user_name, reserved1, reserved2, b.select_key_desc
	from $table_name a Left Join qc_task b ON a.task_id=b.id where $condition order by a.id desc"; 
	//echo $sql;
	echo to_grid_json($db, $sql, $dic_data, array("telephone"=>"blue_color_mapper", 'user_select_key'=>'user_select_key_mapper', 'op_link'=>'op_link_mapper'));

} else if($action == "list_api_log") {
	$condition = "1=1";
	if(isset($_GET['call_id'])) {
		$condition .= " and call_id='".$_GET['call_id']."'";
	}
	$sql = "select id,call_id,invoke_result, update_time,api_url from qc_api_log where $condition order by id desc"; 
	echo to_grid_json($db, $sql, $dic_data, array("call_id"=>"blue_color_mapper", 'invoke_result'=>'invoke_result_mapper'));

} else if($action == "import") { // 导入这里要求文本文件是utf-8编码格式，不然导入有问题；2014/12/15
	$f = fopen($_FILES['upload_file']['tmp_name'], "r");
	$i = 0;
	$dt = date("Y-m-d H:i:s");
	$task_id = $_GET['task_id'];
	$prefix_sql = "insert into qc_call_import(telephone, user_name, reserved1, reserved2, task_id) values ";
	$values_arr = array();
	while(($line=fgets($f)) != "") {
		if( get_str_encoding($line) != 'UTF-8' ) {
			echo "<script> parent.upload_completed(-1);</script>";
			exit;
		}
		$line = str_replace("\n","", $line);
		$line = str_replace("\r","", $line);
		$line = str_replace("，",",", $line);
		$line_arr = split(",", $line);
		$tel = $line_arr[0];
		if( ! preg_match('/([\d]+)/', $tel, $match_arr) ) {
			continue;
		}
		$tel = $match_arr[1]; // 从utf-8字串提取纯数字，以解决第一条是空号的问题; 2014/12/16
		if(strlen($tel)==11 && substr($tel,0,1)=="1" && $_POST['is_auto_add_zero'] == "yes") {
			$tel = "0". $tel;  // 手机号码自动加0
		}
		if((strlen($tel)==7 || strlen($tel)==8) && $_POST['is_auto_add_areacode'] == "yes") {
			$tel = $_POST['areacode']. $tel;  // 固话号码自动加区号 
		}
		$user_name="";
		$reserved1="";
		$reserved2="";
		if( isset($line_arr[1]) ) {
			$user_name=$line_arr[1];
		}
		if( isset($line_arr[2]) ) {
			$reserved1=$line_arr[2];
		}
		if( isset($line_arr[3]) ) {
			$reserved2=$line_arr[3];
		}
		$values_arr[] = "('$tel', '$user_name', '$reserved1', '$reserved2', $task_id)";
		$i++;
		if($i % 1000 == 0) {  // 改成每1000条写一次数据，提升处理效率; 2014/9/17
			$db->query($prefix_sql . implode(",", $values_arr));  
			$values_arr = array();
		}
	}
	if(count($values_arr) > 0) {
		$i = 0;
		$db->query($prefix_sql . implode(",", $values_arr)); // 将非1000整数的剩余记录写入temp表
	}
	$import_count = $i+count($values_arr); // 原始导入条数;

	if($_POST['is_auto_filter_same'] == "yes") {
		// 用中间一次性自动去重，提升效率;
		$sql = "insert into qc_call(telephone, user_name, reserved1, reserved2, post_time, task_id) 
		select distinct telephone, user_name, reserved1, reserved2, '$dt', $task_id from qc_call_import where task_id=$task_id";
		$db->query($sql);
		$import_count = mysql_affected_rows(); // 取到去重后导入的条数
		$db->query("delete from qc_call_import where task_id=$task_id"); // 清除中间表的数据
	}

	$db->query("update qc_task set call_count=call_count+$import_count where id=$task_id"); // 更新任务表的号码条数
	echo "<script> parent.upload_completed(".$import_count.");</script>"; // 提示记录导入条数

}  else if($action == "export_to_excel") {
		$condition = 'a.task_id='.$_GET['task_id'];
		if(isset($_GET['user_select_key'])) {
			$condition .= " and a.user_select_key='".$_GET['user_select_key']."'";
		}
		if(isset($_GET['call_result'])) {
			$condition .= " and a.call_result=".$_GET['call_result'];
		}
		if(isset($_GET['call_status'])) {
			$condition .= " and a.call_status=".$_GET['call_status'];
		}
		if(isset($_GET['date_range'])) {
			$arr = explode("_", $_GET['date_range']);
			$condition .= " and a.call_time between '".$arr[0]."' and '".$arr[1]."'";
		}
		$doc = array();
		$db->query("select *,b.task_name, b.callout_number,b.select_key_desc from qc_call a Left Join qc_task b ON a.task_id=b.id where $condition order by a.id desc");
		$call_result = array(1=>"成功", 2=>"失败");
		while($db->next_record()) {
			$doc[] =  array(
					   htmlspecialchars($db->f("task_name")), 
					   $db->f("callout_number"),
					   $db->f("telephone"), 
					   $call_result[$db->f("call_result")],
					   $db->f("call_time"), 
					   user_select_key_mapper($db->f("user_select_key"), array('select_key_desc'=>$db->f("select_key_desc"))),
					   htmlspecialchars($db->f("user_name")),
					   htmlspecialchars($db->f("reserved1"))
			);
		}
		$xml_excel = new Xml_Excel();
		$xml_excel->setWorksheetTitle("外呼结果明细");
		$xml_excel->addArray ( $doc );  
		$xml_excel->generateXML ("data_export_".date("YmdHis")); 

}  else if($action == "clear") {
	$task_id = $_GET['task_id'];
	$db->query("delete from qc_call where task_id=$task_id");
	$db->query("update qc_task set call_count=0 where id=$task_id"); // 更新任务表的号码条数
	echo "ok"; // 清除已导入的号码数据

}  else if($action == "re_call") {
	$db->query("update qc_call set call_status=0, call_result=NULL, call_time=NULL, fail_desc=NULL, 
	listen_time_long=NULL, user_select_key=NULL  where id=".$_GET['id']); // 清除记录结果值，进行重呼
	echo "ok"; // 重新呼叫

} else if($action == "cancel_call") {
	$db->query("update qc_call set call_status=-1  where id=".$_GET['id']);
	echo "ok"; // 取消呼叫
}



function op_link_mapper($v, $arr) {
	$str = "<a href=\"javascript:re_call(".$arr['id'].")\">重新呼叫</a>";
	if($arr['call_status'] == 0  || $arr['call_status'] == 1) { // 待呼及队列中，都显示取消操作
		$str = "<a href=\"javascript:cancel_call(".$arr['id'].")\" style=\"color:#ff6633\">取消呼叫</a>";
	}
	return $str;
}

function invoke_result_mapper($v) {
	return "<font color=red>". htmlspecialchars($v) ."</font>";
}


function user_select_key_mapper($v, $arr) {
	if($arr['select_key_desc'] != '') {
		$desc_arr = split(",", $arr['select_key_desc']);
		$cnt = count($desc_arr);
		for($i=0; $i<$cnt; $i++) {
			$kv = split(":", $desc_arr[$i]);
			if($kv[0] == $v) return $kv[1];
		}
	}
	return $v;
}

?>